const path = require('path')
const router = require('express').Router()
const multer = require('multer')
const { cmdPromise } = require('./command')
// 文件上传
const storageInfo = multer.diskStorage({
    destination: 'zip/',
    filename(req, file, cb) {
        console.log('file', file);
        cb(null, `${req.query.id}`)
    }
})
const upload = multer({ storage: storageInfo })
router.post('/upload', upload.array('file'), async (req, res) => {
    console.log('req.query', req.query);
    const archivePath = path.join(__dirname, 'zip', req.query.id);
    const extractPath = path.join(__dirname, 'static', req.query.id.split('.')[0]);
    // 1. 解压
    await cmdPromise({
        type: '解压',
        option: 'decompress',
        socketId: req.query.socketId,
        fileName: req.query.id
    },'7z', ['x', `${archivePath}`, `-o${extractPath}`, '-y', '-bsp2'], {
        stdio: ['ignore', 'pipe', 'pipe']
    } );
    console.log('✅ 解压完成');
    // 2. 下载
    await cmdPromise({
        type: '下载',
        option: 'download',
        socketId: req.query.socketId,
        fileName: req.query.id,
        startPage: req.query.startPage,
        endPage: req.query.endPage,
    }, 'node-fs/download.js');
    console.log('✅ 下载完成');
    // 3. 统计
    await cmdPromise({
        type: '统计',
        option: 'statistics',
        socketId: req.query.socketId,
        fileName: req.query.id,
        startPage: req.query.startPage,
        endPage: req.query.endPage,
    }, 'node-fs/create.js');
    console.log('✅ 统计完成');
    // 4. 汇总
    await cmdPromise({
        type: '汇总',
        option: 'collect',
        socketId: req.query.socketId,
        fileName: req.query.id,
        startPage: req.query.startPage,
        endPage: req.query.endPage,
    }, 'node-fs/collect.js');
    console.log('✅ 汇总完成');
    // 5. 压缩
    await cmdPromise({
        type: '压缩',
        option: 'compress',
        socketId: req.query.socketId,
        fileName: req.query.id
    },'7z', ['a', `result/${req.query.id}`, `${path.join(__dirname, 'static', req.query.id.split('.')[0], '数据整理')}`, '-y', '-bsp2'], {
        stdio: ['ignore', 'pipe', 'pipe'],
    });
    console.log('✅ 压缩完成');
    res.send({ code: 200, flag: true, link: `http://localhost:8080/result/${req.query.id}` });
})
router.get('/download', async (req, res) => {
    const filename = req.query.id.split('.')[0] + '.7z'
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.setHeader('Content-Type', 'application/zip');
    res.sendFile(path.join(__dirname, 'result', req.query.id))
})
module.exports = router